import path from 'path';
import express,{Express,Request,Response, NextFunction} from 'express';
import chalk from 'chalk';
import morgan from 'morgan';
import cors from 'cors';
import helmet from 'helmet'
import HttpCodes from 'http-status-codes'

import logRequest from "../src/middleware/logRequest"
import errorMiddleware from "../src/middleware/errorMiddleware";
import HttpException from '../src/modules/httpException';

const app:Express = express();
const PORT=process.env.PORT || 9000

// 中间件
app.use(morgan("dev"));//日志中间件
app.use(cors());//跨域中间件
app.use(helmet());//防止xss攻击中间件
app.use(express.static(path.resolve(__dirname,"public")));//静态资源中间件
app.use(logRequest());//原生http request请求调试中间件
app.use(express.json());//请求头 Content-Type=application/json,json数据解析到req.body上
app.use(express.raw()); //"application/octet-stream"
app.use(express.text());// "application/json"
app.use(express.urlencoded({extended:false}));////请求头 content-type:"application/x-www-form-urlencoded",表单数据解析到req.body上


app.get("/",function(req:Request,res:Response){ 
    res.json({message:"hello get jaasdsa"})
})
app.post("/",function(req:Request,res:Response){
    res.json({message:"hello post jaasdsa"})
})

app.get("/error",function(req:Request,res:Response,next:NextFunction){
    next(new HttpException(HttpCodes.NOT_FOUND,"my 404 not fund"));
})

app.get("/error-async",function(req:Request,res:Response,next:NextFunction){
    // setTimeout(()=>{
    //     next(new HttpException(HttpCodes.NOT_FOUND,"my-async 404 not fund"));
    // },1000)
    
    // 优雅写法
    Promise.resolve().then(()=>{
        throw new HttpException(HttpCodes.NOT_FOUND,"mine-async 404 not fund") 
    }).catch(next);
})

app.use(errorMiddleware);//最后-错误处理中间件

app.listen(PORT,()=>{
    console.log(chalk.green(`服务已在端口:【${PORT}】启动`))
})

